package com.lz.football.module.chat
{
	import com.common.stdlib.StringUtil;
	import com.common.utils.Reflection;
	import com.greensock.TweenLite;
	import com.liangzhong.events.AppEventDispatcher;
	import com.liangzhong.events.ChatEvent;
	import com.liangzhong.events.NotifierEvent;
	import com.liangzhong.model.AppData;
	import com.liangzhong.model.chat.ChatDataConstants;
	import com.liangzhong.model.chat.ChatDataManger;
	import com.liangzhong.model.chat.vo.ChatVo;
	import com.liangzhong.model.friend.vo.FriendVo;
	import com.lz.football.module.friend.DriftView;
	import com.lz.football.module.friend.FriendView;
	
	import common.comp.TabButtonBar;
	
	import flash.display.MovieClip;
	import flash.display.SimpleButton;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.events.TextEvent;
	import flash.text.TextField;
	import flash.ui.Keyboard;
	import flash.utils.Dictionary;
	
	import lz.controls.Alert;
	import lz.controls.LButton;
	import lz.controls.ScrollPolicy;
	import lz.controls.core.UIComponent;
	import lz.controls.text.RichTxt;

	/**
	 *聊天 
	 * @author lake
	 * 
	 */	
	public class ChatView extends UIComponent implements IChatView
	{
		/**
		 *输入文本 
		 */		
		private var txtInput :TextField;
		private var buttonBar:TabButtonBar;
		/**
		 *发送按钮 
		 */
		private var sendBtn:SimpleButton;
		private var _richTxt:RichTxt;
		/**
		 *聊天类型 
		 */
		private var _chatType:int;
		/**
		 * 
		 */
		private var _chatDataManager:ChatDataManger;
		/**
		 *输入文字 
		 */
		private var _inputText:String;
		
		/**
		 *私聊VO 
		 */
		private var _privateChatVo:ChatVo;
		/**
		 *是否可以发送 
		 */
		private var _isSureSend:Boolean;
		
		private var chat_bg:MovieClip;//背景
		private var _contain:Sprite;
		/**
		 *向下按钮  
		 */
		private var downBtn:SimpleButton;
		/**
		 向上 
		 */
		private var upBtn:SimpleButton;
		/**
		 *表情图标  
		 */
		private var faceBtn:SimpleButton;
		/**
		 * 私聊效果 
		 */
		private var privatechateff:MovieClip;
		public function ChatView()
		{
			super();
		}
		/**
		 *初始化 
		 * 
		 */		
		public function initUI(view :Object = null):void
		{
			_symbolSkin = Reflection.createInstance("com.football.module.chat.PanelSkin");
			this.addChild(_symbolSkin);
			//初始化宽高
			width = _symbolSkin.width;
			height = _symbolSkin.height;
			sendBtn = _symbolSkin.sendBtn;
			chat_bg  = _symbolSkin.chat_bg;
			downBtn = _symbolSkin.downBtn;
			upBtn = _symbolSkin.upBtn;
			faceBtn = _symbolSkin.faceBtn;
			upBtn.visible = false;
			_contain = new Sprite();
			_contain.addChild(chat_bg);
			this.addChildAt(_contain,0);
			var faceDic :Dictionary = new Dictionary();
			for(var j:int = 0;j < 42;j++)
			{
				faceDic["/f_" +j ] = "f" + j;
			}
			//初始化组件
			txtInput = _symbolSkin.txtInput;
			txtInput.text = "";
			if(AppData.getInstance().clubDatamanager.clubInfo.playertype != 1)
				txtInput.maxChars = 30;
			buttonBar = new TabButtonBar();
			var i :int = 0;
			var lbtn :LButton;
			var lbtns :Array = [];
			for(;i<=4;i++)
			{
				lbtn = new LButton(_symbolSkin["buttonBar"]["skin_" + i]);
				lbtn.enable = true;
				lbtn.mouseChildren = false;
				lbtns.push(lbtn);
			}
			privatechateff = _symbolSkin["buttonBar"]["privatechateff"];
			privatechateff.stop();
			if(privatechateff.parent)
				privatechateff.parent.removeChild(privatechateff);
			
			buttonBar.setButtons(lbtns);
			buttonBar.selectTabButton(lbtns[0]);
			_chatType = ChatDataConstants.WORLD_CHAT;
			_richTxt = new RichTxt();
			_richTxt.setFaceDic(faceDic);
			_richTxt.maxLines = 50;
			_richTxt.horizontalScrollPolicy = ScrollPolicy.OFF;
			_richTxt.setSize(340,135);
			_richTxt.y = 5;
			_contain.addChild(_richTxt);
//			_contain.y = 10;
			_chatDataManager = AppData.getInstance().chatDataManager;
			addEvtListener();
			
		}
		/**
		 *注册事件 
		 * 
		 */		
		public function addEvtListener():void
		{
			sendBtn.addEventListener(MouseEvent.CLICK,onSendMessageHandler);
			txtInput.addEventListener(KeyboardEvent.KEY_DOWN,onKeyDown);
			AppEventDispatcher.getInstance().addEventListener(NotifierEvent.PRIVATE_CHAT,onPrivateChatHandler);
			buttonBar.addEventListener(Event.CHANGE,onButtonBarHandler);
			_chatDataManager.addEventListener(ChatEvent.GET_MESSAGE,onGetMessageHandler);
			_richTxt.addEventListener(TextEvent.LINK,linkHandler);
			txtInput.addEventListener(Event.CHANGE,onTextChangeHandler);
			this.addEventListener(Event.ADDED_TO_STAGE,onAddStageHandler);
			downBtn.addEventListener(MouseEvent.CLICK,ondownHandler);
			upBtn.addEventListener(MouseEvent.CLICK,onUPHandler);
				
			AppEventDispatcher.getInstance().addEventListener(ChatEvent.CHAT_FACE,onChatFaceHandler);
			faceBtn.addEventListener(MouseEvent.CLICK,onFacehandler);
			
		}
		
		protected function onFacehandler(event:MouseEvent):void
		{
			// TODO Auto-generated method stub
			FaceView.instance.showView();
		}
		
		protected function onChatFaceHandler(event:ChatEvent):void
		{
			// TODO Auto-generated method stub
			//if(txtInput.text.length > 30)return;
			txtInput.appendText(event.param);
//			txtInput.text += event.param;
//			var str:String = txtInput.text;
//			str.
		}
		
		protected function onUPHandler(event:MouseEvent):void
		{
			// TODO Auto-generated method stub
			_contain.mouseChildren = true;
			_contain.mouseEnabled =true;
			upBtn.visible = false;
			downBtn.visible = true;
			TweenLite.to(_contain,0.5,{y:0,alpha:1});
		}
		
		protected function ondownHandler(event:MouseEvent):void
		{
			
			_contain.mouseChildren = false;
			_contain.mouseEnabled =false;
			upBtn.visible = true;
			downBtn.visible = false;
			TweenLite.to(_contain,0.5,{y:140,alpha:0});
		}
		/**
		 *私聊名称 不为  "密"+ _privateChatVo.name + "："时，清除名称 
		 * @param event
		 * 
		 */		
		protected function onTextChangeHandler(event:Event):void
		{
			// TODO Auto-generated method stub
			
			if(_privateChatVo == null)return;
			var str:String = txtInput.text;
			str =  txtInput.text;
			var n:String = "密"+ _privateChatVo.name + "：";
			if(str.indexOf(n) != 0)// 是否为名称第一个
			{
				txtInput.text = "";
				_privateChatVo = null;
			}
			
		}
		/**
		 *添加到舞台上 
		 * @param event
		 * 
		 */		
		protected function onAddStageHandler(event:Event):void
		{
			// TODO Auto-generated method stub
			this.stage.addEventListener(MouseEvent.MOUSE_UP,onStageDownHandler);
		}
		
		/**
		 *点击舞台 移除光标
		 * @param event
		 * 
		 */
		protected function onStageDownHandler(event:MouseEvent):void
		{
			if(event.target == txtInput || event.target == sendBtn)
			{
				txtInput.addEventListener(KeyboardEvent.KEY_DOWN,onKeyDown);
				return;
			}
			if(event.target.parent == this || event.currentTarget.parent == this)
			{
				return;
			}
			//this.stage.focus = null;
			txtInput.removeEventListener(KeyboardEvent.KEY_DOWN,onKeyDown);
		}
		/**
		 *按钮enter键  
		 * @param event
		 * 
		 */		
		private function onKeyDown(event:KeyboardEvent):void
		{
			if(event.keyCode == Keyboard.ENTER)
			{
				onSendMessageHandler();
			}
		}
		/**
		 *点击连接文本 
		 * @param event
		 * 
		 */
		protected function linkHandler(event:TextEvent):void
		{
			var str:String = event.text;
			var arr:Array = str.split(/_/g);
			var friendVo:FriendVo = new FriendVo();
			friendVo.friendid = arr[0];;
			friendVo.uname = arr[1];
			DriftView.instance.friendVo = friendVo;
		}
		
		/**
		 *获得新的聊天信息 
		 * @param event
		 * 
		 */
		protected function onGetMessageHandler(event:ChatEvent):void
		{
			var chatVo:ChatVo = event.param.vo;
			if(_chatType == chatVo.ntype || (chatVo.ntype == ChatDataConstants.ALL_CHAT && _chatType == ChatDataConstants.WORLD_CHAT))
			{
				_richTxt.appendHtmlText(chatVo.pFormat);
//				_richTxt.verticalPageScrollSize = 200;
//				if(_richTxt.lines > 50)1
//					_richTxt.deleteFirstLine();
			}
			if(_chatType != ChatDataConstants.PRIVATE_CHAT && chatVo.ntype == ChatDataConstants.PRIVATE_CHAT)//获得私聊信息，但tab按钮不是私聊 因此私聊按钮需要闪烁
			{
				_symbolSkin["buttonBar"].addChild(privatechateff);
				privatechateff.gotoAndPlay(1);
			}
		
		}
		
		/**
		 *选择了按钮 
		 * @param event
		 * 
		 */
		protected function onButtonBarHandler(event:Event):void
		{
			// TODO Auto-generated method stub
			var arr:Array ;
			switch(buttonBar.selectType)
			{
				case 0:
					_chatType = ChatDataConstants.WORLD_CHAT;
					arr = _chatDataManager.allChat;
					break;
				case 1:
					_chatType = ChatDataConstants.WORLD_CHAT;
					arr = _chatDataManager.worldChat;
					break;
				case 2:
					_chatType = ChatDataConstants.ALLIANCE_CHAT;
					arr = _chatDataManager.allianceChat;
					break;
				case 3:
					_chatType = ChatDataConstants.COUNTRY_CHAT;
					arr = _chatDataManager.countryChat;
					break;
				case 4:
					_chatType = ChatDataConstants.PRIVATE_CHAT;
					arr = _chatDataManager.privateChat;
					
					privatechateff.stop();
					if(privatechateff.parent)
						privatechateff.parent.removeChild(privatechateff);
					break;
			}
			txtInput.text = "";
			this.stage.focus = txtInput;
			_privateChatVo = null;
//			txtInput.setSelection(txtInput.text.length,txtInput.text.length);
//			upData();
			
			if(_richTxt.lines > 0)_richTxt.clear();
			var len:int = arr.length;
			for(var i:int = 0;i < len;i++)
			{
				_richTxt.appendHtmlText(arr[i]);
			}
			_richTxt.update();
		}
		
		
		/**
		 *私聊 
		 * @param event
		 * 
		 */
		protected function onPrivateChatHandler(event:NotifierEvent):void
		{
			// TODO Auto-generated method stub
			if(event.params.vo.id == AppData.getInstance().clubDatamanager.clubInfo.clubid)
			{
				Alert.showErrorTip("不可以同自己私聊");
				return;
			}
			buttonBar.setTabButtonByIndex(4);
			_privateChatVo = event.params.vo;
			setPrivate();
		}
		/**
		 *设置私聊 
		 * 
		 */
		private function setPrivate():void
		{
			if(_privateChatVo == null)return;
			txtInput.text ="密"+ _privateChatVo.name + "：";
			this.stage.focus = txtInput;
			txtInput.setSelection(txtInput.text.length,txtInput.text.length);
		}
		/**
		 *发送消息 
		 * @param event
		 * 
		 */
		protected function onSendMessageHandler(event:Event = null):void
		{
			var str:String;
			var tip:String
			var vo:ChatVo = new ChatVo();
			if(_isSureSend)
			{
				//发言过快
//				trace("发言过快");
				tip = "<font color = '#FF0000'>【系统】您发信息的速度太快，请稍后重新发送。</font>"
				_richTxt.appendHtmlText(tip);
//				_richTxt.verticalPageScrollSize = 200;
				_chatDataManager.checkType(_chatType,tip);
				return 
			}
			
			
			if(_chatType == ChatDataConstants.PRIVATE_CHAT)//私聊
			{
				tip = "<font color = '#FF0000'>【系统】请选择私聊对象。</font>"
				if(_privateChatVo == null )
				{
					_richTxt.appendHtmlText(tip);
					_chatDataManager.checkType(_chatType,tip);
					return;
				}
				str =  txtInput.text;
				var n:String = "密"+ _privateChatVo.name + "：";
				if(str.indexOf(n) != 0)// 是否为名称第一个
				{
					_richTxt.appendHtmlText(tip);
					_chatDataManager.checkType(_chatType,tip);
					return;
				}
				
				str = str.replace(n,"");
				vo.id = _privateChatVo.id;
			}else//其他的聊天类型
			{
				vo.id = 0;
				str = txtInput.text
			}
			str = StringUtil.trim(str);
			if(str == "")
			{
				Alert.showErrorTip("请输入文字");
				return;
			}
			vo.name = AppData.getInstance().clubDatamanager.clubInfo.uname;
			vo.ntype = _chatType;
			vo.pFormat = str;
			txtInput.text = "";
			if(_chatType == ChatDataConstants.PRIVATE_CHAT)
				setPrivate();
//			trace(str);
			this.dispatchEvent(new ChatEvent(ChatEvent.SEND_MESSAGE,{vo:vo}));
			_isSureSend = true;
			TweenLite.delayedCall(4,onTweenLite);
			if(_chatType == ChatDataConstants.WORLD_CHAT)
			{
				return;
			}
			vo.id = AppData.getInstance().clubDatamanager.clubInfo.clubid;
			vo.country = AppData.getInstance().clubDatamanager.clubInfo.country;
			vo.playertype = AppData.getInstance().clubDatamanager.clubInfo.playertype;
			_chatDataManager.assemble(vo);
			_richTxt.appendHtmlText(vo.pFormat);
			//_richTxt.verticalScrollPosition = 200;
			
			
		}
		/**
		 *三秒后才可以发言 
		 * 
		 */		
		private function onTweenLite():void
		{
			_isSureSend = false;
		}
		/**
		 *删除事件 
		 * 
		 */		
		public function removeEvtListener():void
		{
			
		}
		/**
		 *销毁 
		 * 
		 */		
		public function destroyView():void
		{
			
		}
		/**
		 *显示tab类型 
		 * @param $obj
		 * 
		 */
		public function showType($obj:Object):void
		{
			
		}
		/////////////////////////interfaces///////////////////////////
		/**
		 *获取聊天信息  
		 * @param $obj
		 * 
		 */
		public function getMessage($obj:Object):void
		{
			
		}
	}
}